package org.seamon.management.util.exception;

import io.jsonwebtoken.JwtException;
import org.seamon.management.util.Result;
import org.seamon.management.util.enums.ErrorCodeEnum;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author Simon
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(BusinessException.class)
    public Result<?> handleBusinessException(BusinessException ex) {
        return Result.error(ex.getErrorCodeEnum(), ex.getMessage());
    }

    // 处理权限拒绝异常
    @ExceptionHandler(AccessDeniedException.class)
    public Result<?> handleAccessDeniedException() {
        return Result.error(ErrorCodeEnum.FORBIDDEN);
    }

    // 处理JWT异常
    @ExceptionHandler(JwtException.class)
    public Result<?> handleJwtException() {
        return Result.error(ErrorCodeEnum.TOKEN_INVALID);
    }

    // 处理Spring Security认证异常
    @ExceptionHandler(AuthenticationServiceException.class)
    public Result<?> handleAuthenticationServiceException() {
        return Result.error(ErrorCodeEnum.USER_NOT_EXIST);
    }

    // 处理限流异常
    @ExceptionHandler(LimitException.class)
    public Result<?> handleLimitException(LimitException ex) {
        return Result.error(ErrorCodeEnum.TOO_MANY_REQUESTS);
    }

    // 捕获所有运行时异常
    @ExceptionHandler(RuntimeException.class)
    public Result<?> handleRuntimeException(RuntimeException ex) {
        int code = ErrorCodeEnum.INTERNAL_SERVER_ERROR.getCode();
        StringBuilder message = new StringBuilder(ErrorCodeEnum.INTERNAL_SERVER_ERROR.getMessage());
        if (ex.getCause() != null) {
            message.append(": ").append(ex.getCause());
        }
        return Result.error(code, message.toString());
    }
}
